import { createRouter, createWebHistory } from "vue-router";
import { staticRouter, errorRouter } from "@/routers/modules/staticRouter";
import { useAuthStore, useUserStore } from "@/stores";
import { npProgress, LOGIN_URL } from "@/config";
import { getEnv } from "@/utils/getEnv";
import { initDynamicRouter } from "./modules/dynamicRouter";
import { usePermissionStore } from "@/stores/index";

/**
 * @description 创建路由实例
 */
const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [...staticRouter, ...errorRouter],
  strict: false,
  scrollBehavior: (_, __, savedPosition) => (savedPosition ? savedPosition : { left: 0, top: 0 })
});

/**
 * @description 路由拦截器
 * @param {RouteLocationNormalized} to 去的路由
 * @param {RouteLocationNormalized} from 来的路由
 * @param {NavigationGuardNext} next 下行回调
 */
router.beforeEach(async (to, from, next) => {
  const usePermission = usePermissionStore();
  if (
    !usePermission.permissions.includes("*:*:*") &&
    to.meta.permissions &&
    !usePermission.permissions.some((item) => item === to.meta.permissions)
  ) {
    next("/403");
  }
  const useUser = useUserStore();
  const useAuth = useAuthStore();
  npProgress.start();

  const title = getEnv("VITE_GLOB_APP_TITLE");
  document.title = to.meta.title ? `${to.meta.title} - ${title}` : title;

  if (useUser.token === "" && to.path !== LOGIN_URL) {
    return next({ path: LOGIN_URL, replace: true });
  }
  if (useUser.token !== "" && to.path === LOGIN_URL) {
    return next({ path: from.fullPath });
  }
  if (!useAuth.userMenu.length && useUser.token !== "") {
    await initDynamicRouter();
    return next({ ...to, replace: true });
  }
  return next();
});

/**
 * @description 路由跳转出错拦截
 */
router.onError(() => {
  npProgress.done();
});

/**
 * @description 路由跳转结束拦截
 */
router.afterEach(() => {
  npProgress.done();
});

export default router;
